package com.s63.springboot3.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.s63.springboot3.entity.AjaxResult;
import com.s63.springboot3.entity.User;
import com.s63.springboot3.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public AjaxResult getAll(@RequestParam(required = false, defaultValue = "1") int pageNum,
                             @RequestParam(required = false, defaultValue = "2") int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userService.getAll();
        PageInfo<User> pageInfo = PageInfo.of(list);
        return AjaxResult.ok(pageInfo);
    }

    @GetMapping("/{id}")
    public AjaxResult get(@PathVariable Integer id) {
        User user = userService.get(id);
        return AjaxResult.ok(user);
    }

    @PostMapping
    public AjaxResult add(@RequestBody User user) {
        userService.add(user);
        return AjaxResult.ok();
    }

    @DeleteMapping("/{id}")
    public AjaxResult del(@PathVariable Integer id) {
        userService.del(id);
        return AjaxResult.ok();
    }

    @PutMapping
    public AjaxResult update(@RequestBody User user) {
        userService.update(user);
        return AjaxResult.ok();
    }
}
